/**
 * 1. 链表结构 node+head+null
 * 2. 链表为空时 head --> null
 * 3. 用于维护node节点个数的属性 size
 * 
 * 4. node节点 指向下一个节点的属性next 具体的内容属性element
 * 
 * 5. 操作行为: 增加 删除 修改 查询 清空
 */
class Node{
  constructor(element, next){
    this.element = element
    this.next = next
  }
}

class LinkedList{
  constructor(head, size){
    this.head = null
    this.size = 0
  }
  _getNode(index){
    if (index<0||index>=this.size){
      console.log('越界了')
      return
    }
    let currentNode = this.head
    for(let i=0;i<index;i++){
      currentNode = currentNode.next
    }
    return currentNode
  }
  add(index, element){
    // 只输入一个参数，改参数为内容，默认位置为最后
    if(arguments.length === 1){
      element = index
      index = this.size
    }
    // 越界判断
    if(index<0||index>this.size){
      console.log('error! cross the border')
      return
    }
    if(index == 0){//在头部添加
      let head = this.head // 保存原有 head 指向
      this.head = new Node(element, head);
    }else{//在中间或尾部添加
      let prevNode = this._getNode(index-1) // 上一个节点
      prevNode.next = new Node(element, prevNode.next)
    }
    this.size++
  }
  remove(index){
    // 删除第一个
    if(index === 0){
      let head = this.head
      this.head = head.next
    }else{// 删除非第一个
      let prevNode = this._getNode(index-1)
      prevNode.next = prevNode.next.next
    }
    this.size--
  }
  set(index,element){
    let node = this._getNode(index)
    node.element = element
  }
  get(index){
    return this._getNode(index)
  }
  clear(){
    this.head = null
    this.size = 0
  }
}

const l1 = new LinkedList()
l1.add('node1')
l1.add('node2')
l1.add(1,'node3')
// l1.remove(1)
l1.set(1,'node3-3')
l1.clear()
console.log(l1)
